package com.hgkj.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.hgkj.common.core.domain.ApiResult;
import com.hgkj.common.core.domain.BaseController;
import com.hgkj.common.core.utils.AssertExceptionUtils;
import com.hgkj.common.log.annotation.TimeCount;
import com.hgkj.system.domain.SysRole;
import com.hgkj.system.domain.dto.request.AssignRoleMenu;
import com.hgkj.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

@Validated
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService roleService;

    /**
     * 分页查询角色信息
     *
     * @param role 查询条件
     * @return 分页数据
     */
    @GetMapping
    @TimeCount(threshold = 2000, description = "角色查询接口")
    @SaCheckPermission("system.role.list")
    public ApiResult list(SysRole role) {
        startPage();
        List<SysRole> roles = roleService.getRoleList(role);
        return getTableData(roles);
    }

    /**
     * 添加角色数据
     *
     * @param role role
     * @return resp
     */
    @PostMapping
    @SaCheckPermission("system.role.add")
    public ApiResult add(@Valid @RequestBody SysRole role) {
        return getResult(roleService.insertRole(role));
    }

    /**
     * 修改角色信息
     *
     * @param role roleInfo
     * @return Resp
     */
    @PutMapping
    @SaCheckPermission("system.role.edit")
    public ApiResult update(@Valid @RequestBody SysRole role) {
        AssertExceptionUtils.notNull(role.getRoleId(), "roleId字段不能为空");
        return getResult(roleService.updateRole(role));
    }

    /**
     * 删除角色信息
     *
     * @param roleId roleId
     * @return Response
     */
    @DeleteMapping("/{roleId}")
    @SaCheckPermission("system.role.remove")
    public ApiResult delete(@PathVariable @NotNull(message = "角色ID不能为空")
                            @Min(value = 1, message = "角色ID必须大于0") Long roleId) {
        return getResult(roleService.deleteRole(roleId));
    }

    /**
     * 查询角色已分配权限菜单
     * @param roleId 角色ID
     * @return 分配菜单
     */
    @GetMapping("/assign/{roleId}")
    @SaCheckPermission("system.role.assign")
    public ApiResult assignList(@PathVariable @NotNull(message = "角色ID不能为空")
                                @Min(value = 2, message = "角色ID必须大于1") Long roleId) {
        return success(roleService.assignList(roleId));
    }

    /**
     * 分配角色权限
     * @param assignRoleMenu request
     * @return Response
     */
    @PutMapping("/assign")
    @SaCheckPermission("system.role.assign")
    public ApiResult assign(@Valid @RequestBody AssignRoleMenu assignRoleMenu){
        roleService.assign(assignRoleMenu);
        return success();
    }

}
